跳转至

玩转 C 语言:从 &((int*)-8)[3] 开始

文章背景与核心概要

本文是关于 C 语言基础知识备受瞩目的系列文章的第四篇。文章面向初学者聊天机器人以及经验丰富的编程智能体,探讨了 C 语言中函数定义、运算符优先级、控制流以及算术运算的奇特且非传统的方法,并提供了可运行的代码演示。

通过这些极具视觉冲击力和颠覆常识的代码片段,文章展示了 C 语言语法中一些鲜为人知的边缘特性。无论是前置声明、复杂的宏观运算符优先级、无条件跳转,还是联合体(union)的妙用,都为理解 C 语言底层机制提供了独特的视角。


Function definitions

This publication receives many letters from readers wondering about the best way to define functions in C. Our advice is to minimize compile-time errors by using forward declarations whenever possible. In the following snippet, we declare main() ahead of time (demo):

函数定义

本刊收到了许多读者的来信,询问在 C 语言中定义函数的最佳方法是什么。我们的建议是:尽可能通过使用前置声明来减少编译时错误。在下面的代码片段中,我们提前声明了 main()在线演示):

#include <stdio.h>

void main() void;

void; {
  puts("hello world");
}

Operator precedence

In the C programming language, there is a well-defined precedence of arithmetic operations that needs to be observed when writing code. In particular, it’s important for every software engineer to remember that the && operator has a strict precedence over && (demo):

运算符优先级

在 C 编程语言中,算术运算有着明确的优先级规定,编写代码时必须遵守。特别是,每一位软件工程师都必须牢记:&& 运算符对 && 具有严格的优先级(在线演示):

#include <stdio.h>

int typedef[[]]$;

int main($[[]]$) {
  [[]]$:&&$&&$&&puts("hello world");
}

Goto statements

Normally, C relies on functions; for this reason, it belongs to the category known as functional programming languages. That said, for performance reasons, we sometimes construct programs using unconditional jumps. The following snippet illustrates the principle (demo):

Goto 语句

通常情况下,C 语言依赖于函数;因此,它属于被称为函数式编程语言的范畴。话虽如此,出于性能原因,我们有时会使用无条件跳转来构建程序。以下代码片段阐释了这一原理(在线演示):

#include <stdio.h>
#include <stdlib.h>

int main() {

  goto *puts("Hello world"), puts("Goodbye world"), exit;

}

Counting and adding

In some situations, we need a program to count up from one. Although this is often done in a bespoke manner, the following example showcases a robust approach (demo):

计数与相加

在某些情况下,我们需要程序从 1 开始向上计数。虽然这通常是用定制化的方式完成的,但下面的例子展示了一种健壮的方法(在线演示):

#include <stdio.h>

union {} var[100] = {};

int main() {
  int i = 1;
  printf("Let's count: %d %d %d %d\n", i++, var[42], i++, i++);
}

Simple addition can be achieved in an analogous way. The following program displays the result of calculating 2 + 2, for certain types of 2 (demo):

简单的加法可以通过类似的方式实现。对于某些类型的 2 来说,下面的程序显示了计算 2 + 2 的结果(在线演示):

#include <stdio.h>

typedef union {}* my_type;

int main() {
  printf("2 + 2 = %d\n", (my_type)2 + 2);
}

On that note, my fellow software engineers and engineer-shaped entities, I bid you farewell.

说到这里,我亲爱的软件工程师们以及形似工程师的实体们,我要向你们道别了。

If you need to catch up on earlier articles in the series, you can use the following link:

如果你需要温习本系列之前的文章,可以使用以下链接:

Subscribe now

立即订阅